import { useEffect } from 'react';
import usePersistFn from './usePersistFn';

function useTimeout(fn: () => void, delay: number | undefined | null): void {
  let timerFn = usePersistFn(fn);

  useEffect(() => {
    if (delay === null || delay === undefined) return;

    let timer = setTimeout(() => {
      timerFn();
    }, delay);

    return () => {
      clearTimeout(timer);
    };
  }, [delay, timerFn]);
}

export default useTimeout;
